import { login, logout, reqGetInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, asyncRoutes, constantRoutes, anyRoutes } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    routes: [],
    buttons: [],
    roles: [],
    //对比【项目中已有的异步路由，与服务器返回的标记信息进行对比】后需要展示的路由
    resultAsyncRoutes: [],
    resultAllRoutes: [],
    isLogin: false,
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_LOGIN: (state, status) => {
    state.isLogin = status
  },
  // SET_NAME: (state, name) => {
  //   state.name = name
  // },
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // },

  SET_USERINFO: (state, userInfo) => {
    //用户名
    state.name = userInfo.name
    //用户头像
    state.avatar = userInfo.avatar
    //菜单权限标记
    state.routes = userInfo.routes
    //按钮权限标记
    state.buttons = userInfo.buttons
    //角色
    state.roles = userInfo.roles
  },
  SET_RESULTROUTES: (state, asyncRoutes) => {
    state.resultAsyncRoutes = asyncRoutes
    state.resultAllRoutes = constantRoutes.concat(state.resultAsyncRoutes, anyRoutes)
    console.log(state.resultAllRoutes, "++++++");
  }
}

const actions = {
  // user login
  async login({ commit }, userInfo) {
    const { username, password } = userInfo
    let result = await login({ username: username.trim(), password: password })
    if (result.code == 20000) {
      commit('SET_TOKEN', result.data.token)
      setToken(result.data.token)
      return 'ok'
    } else {
      return Promise.reject(new Error('fail'))
    }
    // return new Promise((resolve, reject) => {
    //   login({ username: username.trim(), password: password }).then(response => {
    //     const { data } = response
    //     commit('SET_TOKEN', data.token)
    //     setToken(data.token)
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // get user info
  getInfo({ commit, state }) {
    commit('SET_RESULTROUTES', computedAsyncRoutes(asyncRoutes, asyncRoutes))
    // return new Promise((resolve, reject) => {
    //   reqGetInfo(state.token).then(response => {
    //     const { data } = response

    //     if (!data) {
    //       return reject('Verification failed, please Login again.')
    //     }

    //     // const { name, avatar } = data
    //     // console.log(data);
    //     // commit('SET_NAME', name)
    //     // commit('SET_AVATAR', avatar)

    //     commit('SET_USERINFO', data)
    //     commit('SET_RESULTROUTES', computedAsyncRoutes(asyncRoutes, data.routes))
    //     resolve(data)
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },



  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

// //定义一个函数：两个数组进行对比，对比出当前用户需要显示哪些异步路由
// const computedAsyncRoutes = (asyncRoutes, routes) => {
//   return asyncRoutes.filter(item => {
//     if (routes.indexOf(item.name) != -1) {
//       if (item.children && item.children.length) {
//         item.children = computedAsyncRoutes(item.children, routes)
//       }
//       return true
//     }
//   })
// }

//定义一个函数：两个数组进行对比，对比出当前用户需要显示哪些异步路由
const computedAsyncRoutes = (asyncRoutes, routes) => {
  return asyncRoutes
}





export default {
  namespaced: true,
  state,
  mutations,
  actions
}

